﻿using System;

using UnityEngine;
using UnityEngine.EventSystems;

/// <summary>
/// Simple example script of how a button can be rotated visibly when the mouse hovers over it or it gets pressed.
/// </summary>

[AddComponentMenu("UGUI/Interaction/Button Rotation")]
public class UGUIButtonRotation : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler, ISelectHandler, IDeselectHandler
{
	public Transform tweenTarget;
	public Vector3 hover = Vector3.zero;
	public Vector3 pressed = Vector3.zero;
	public float duration = 0.2f;

	Quaternion mRot;
	bool mStarted = false;

	void Start ()
	{
		if (!mStarted)
		{
			mStarted = true;
			if (tweenTarget == null) tweenTarget = transform;
			mRot = tweenTarget.localRotation;
		}
	}

	void OnEnable () { }

	void OnDisable ()
	{
		if (mStarted && tweenTarget != null)
		{
			UGUITweenRotation tc = tweenTarget.GetComponent<UGUITweenRotation>();

			if (tc != null)
			{
				tc.value = mRot;
				tc.enabled = false;
			}
		}
	}

	void OnPress (bool isPressed)
	{
		if (enabled)
		{
			if (!mStarted) Start();
			UGUITweenRotation.Begin(tweenTarget.gameObject, duration, isPressed ? mRot * Quaternion.Euler(pressed) : mRot).method = UGUITweener.Method.EaseInOut;
		}
	}

	void OnHover (bool isOver)
	{
		if (enabled)
		{
			if (!mStarted) Start();
			UGUITweenRotation.Begin(tweenTarget.gameObject, duration, isOver ? mRot * Quaternion.Euler(hover) :
				mRot).method = UGUITweener.Method.EaseInOut;
		}
	}

	void OnSelect (bool isSelected)
	{
        if (enabled)
        {
            OnHover(isSelected);
        }
	}

    public void OnPointerDown(PointerEventData eventData)
    {
        OnPress(true);
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        OnPress(false);
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        OnHover(true);
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        OnHover(false);
    }

    public void OnSelect(BaseEventData eventData)
    {
        OnSelect(true);
    }

    public void OnDeselect(BaseEventData eventData)
    {
        OnSelect(false);
    }
}
